package cn.backflow.utils;

import java.util.LinkedHashMap;

/**
 * Object for JSON response
 * Created by backflow on 2015/12/24 16:26
 */
public class JsonMap extends LinkedHashMap<String, Object> {

    private static final String successKey = "success";
    private static final String msgKey = "msg";

    public JsonMap() {
    }

    public JsonMap(boolean success) {
        put(successKey, success);
    }

    public JsonMap(boolean success, String msg) {
        put(successKey, success);
        put(msgKey, msg);
    }

    public static JsonMap succeed() {
        return new JsonMap(true);
    }

    /**
     * 创建success为<code>false</code>的实例
     *
     * @param msgs 可选的一组消息
     */
    public static JsonMap fail(String... msgs) {
        JsonMap json = new JsonMap(false);
        if (msgs.length > 0) {
            json.msg(Strings.join(msgs, "\r\n"));
        }
        return json;
    }

    public JsonMap put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public JsonMap success(boolean success) {
        return put(successKey, success);
    }

    public JsonMap msg(String format, Object... args) {
        if (format == null) return this;
        return put(msgKey, String.format(format, args));
    }

    public JsonMap child(String name) {
        JsonMap child = (JsonMap) get(name);
        if (child == null) {
            child = new JsonMap();
            this.put(name, child);
        }
        return child;
    }

    public String msg() {
        return get(msgKey).toString();
    }
}
